/**
 * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.form.service;

import com.alibaba.fastjson.JSON;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.persistence.dialect.Dialect;
import com.jeeplus.core.persistence.interceptor.SQLHelper;
import com.jeeplus.modules.form.entity.Column;
import com.jeeplus.modules.form.entity.Form;
import com.jeeplus.modules.form.utils.FormOracleTableBuilder;
import com.jeeplus.modules.form.utils.FormTableBuilder;
import com.jeeplus.modules.sys.service.AreaService;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 数据表单Service
 *
 * @author 刘高峰
 * @version 2019-12-24
 */
@Service
@Transactional(readOnly = true)
public class GenerateFormService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private OfficeService officeService;
    @Autowired
    private AreaService areaService;

    /**
     * 更新表单
     *
     * @param data
     * @return
     */
    @Transactional(readOnly = false)
    public void executeUpdate(Form form, Map data, HashMap map) {
        //保存表单数据
        FormTableBuilder formTableBuilder;
        String dbType = FormTableBuilder.getJdbcType();
        if(dbType.equals("oracle")){
            formTableBuilder = new FormOracleTableBuilder(jdbcTemplate, form.getTableName());
        }else {
            formTableBuilder = new FormTableBuilder(jdbcTemplate, form.getTableName());
        }
        formTableBuilder.executeUpdate(form, data, map);
    }

    /**
     * 保存表单
     *
     * @param data
     * @return
     */
    @Transactional(readOnly = false)
    public void executeInsert(Form form, Map data, Map map) {
        //保存表单数据
        FormTableBuilder formTableBuilder;
        String dbType = FormTableBuilder.getJdbcType();
        if(dbType.equals("oracle")){
            formTableBuilder = new FormOracleTableBuilder(jdbcTemplate, form.getTableName());
        }else {
            formTableBuilder = new FormTableBuilder(jdbcTemplate, form.getTableName());
        }
        formTableBuilder.executeInsert(form, data, map);

    }
    /**
     * 删除表单内容
     *
     * @return
     */
    @Transactional(readOnly = false)
    public void executeDelete(Form form, String ids) {
        FormTableBuilder formTableBuilder;
        String dbType = FormTableBuilder.getJdbcType();
        if(dbType.equals("oracle")){
            formTableBuilder = new FormOracleTableBuilder(jdbcTemplate, form.getTableName());
        }else {
            formTableBuilder = new FormTableBuilder(jdbcTemplate, form.getTableName());
        }
        formTableBuilder.executeDelete(form, ids);
    }

    /**
     * 查询表单内容
     *
     * @return
     */
    @Transactional(readOnly = true)
    public Map executeQueryById(Form form, String id) {
        FormTableBuilder formTableBuilder;
        String dbType = FormTableBuilder.getJdbcType();
        if(dbType.equals("oracle")){
            formTableBuilder = new FormOracleTableBuilder(jdbcTemplate, form.getTableName());
        }else {
            formTableBuilder = new FormTableBuilder(jdbcTemplate, form.getTableName());
        }
        return formTableBuilder.executeQueryById(form, id);
    }


    public Page<Map> executeFindPage(Page page, Form form, String params, String fields){
        String originalSql = "select * from "+form.getTableName()+" ";
        Map <String, String>paramsMap = JSON.parseObject(params, Map.class);
        List<Column> fieldArra = JSON.parseArray(fields, Column.class);
        HashMap<String, String> typeMap = new HashMap();
        for(Column column: fieldArra){
            typeMap.put(column.getModel(), column.getType());
        }
        if(paramsMap.size() > 0){
            originalSql = originalSql + "where ";
            for (String key : paramsMap.keySet()) {
                originalSql = originalSql + " " + key + " like " + "'%"+String.valueOf(paramsMap.get(key))+"%' and ";
            }
            originalSql = originalSql.substring(0, originalSql.length() - 4);
        }
        if(StringUtils.isNotBlank(page.getOrderBy())){
            originalSql = originalSql + " order by " + page.getOrderBy();
        }
        Dialect dialect = FormTableBuilder.getDialect();
        final String countSql = "select count(1) from (" + dialect.getCountString(originalSql) + ") tmp_count";
        int count = jdbcTemplate.queryForObject(countSql, Integer.class);
        page.setCount(count);
        String pageSql = SQLHelper.generatePageSql(originalSql, page, dialect);
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(pageSql);

        for (Map<String, Object> map : mapList) {
            for (String key : map.keySet()) {
                if("user".equals(typeMap.get(key))){
                    if(map.get(key) != null && UserUtils.get(map.get(key).toString())!=null){
                        map.put(key, UserUtils.get(map.get(key).toString()).getName());
                    }
                }
                if("office".equals(typeMap.get(key))){
                    if(map.get(key) != null && officeService.get(map.get(key).toString())!=null){
                        map.put(key, officeService.get(map.get(key).toString()).getName());
                    }
                }
                if("area".equals(typeMap.get(key))){
                    if(map.get(key) != null && areaService.get(map.get(key).toString())!=null){
                        map.put(key, areaService.get(map.get(key).toString()).getName());
                    }
                }
            }
        }
        page.setCount(count);
        page.setList(mapList);
        return page;
    }


}
